package com.github.operationlog.command;

import com.github.operationlog.MethodAttribute;
import com.github.operationlog.output.OperationLogOutput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

/**
 * Delete操作方法命令
 *
 * @author luke.luo
 */
@Slf4j
public class DeleteOperationCommand extends OperationCommand {

    public DeleteOperationCommand(String table, Object target, MethodAttribute methodAttribute,
                                  Method findByIdMethod, OperationLogOutput operationLogOutput) {
        super(table, target, methodAttribute, findByIdMethod, operationLogOutput);
        methodAttribute.setEntityParam(false);
    }

    @Override
    public Object execute0(Object target, Method method, Object[] args, Object entityId) {
        Object entity = findById(entityId);
        if (entity == null) {
            log.warn("实体删除方法记录日志失败，原因：根据实体ID未查询到旧实体，updateMethod={}#{}, entityId={}",
                    methodAttribute.getTargetName(), method.getName(), entityId);
            return ReflectionUtils.invokeMethod(method, target, args);
        }

        Object returnValue = ReflectionUtils.invokeMethod(method, target, args);
        insertLog(args[0], buildEntityOldValue(entity));
        return returnValue;
    }
}